﻿// -----------------------------------------------------------------------
// <copyright file="PackageConsoleManager.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace NeosSDI.VsExtension
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.VisualStudio.Shell;
    using NuGetConsole.Implementation;
    using System.Reflection;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class PackageConsoleManager
    {
        EnvDTE.DTE dte = null;
        Package package;
        object wpfConsole;
        object dispatch;
        object powerConsoleToolWindow;
        public PackageConsoleManager(EnvDTE.DTE dte, Package package)
        {
            this.package = package;
            this.dte = dte;
            DisplayConsole();
            powerConsoleToolWindow = (PowerConsoleToolWindow)package.FindToolWindow(typeof(PowerConsoleToolWindow), 0, false);
            var prop = powerConsoleToolWindow.GetType().GetProperty("WpfConsole", BindingFlags.NonPublic | BindingFlags.Instance);
            var t = prop.GetValue(powerConsoleToolWindow, null);
            var prop1 = t.GetType().GetField("_impl", BindingFlags.NonPublic | BindingFlags.Instance);
            wpfConsole = prop1.GetValue(t);

            // get dispatcher
            dispatch = wpfConsole.GetType().GetProperty("Dispatcher").GetValue(wpfConsole, null);
            

        }

        internal void DisplayConsole()
        {
            var powerConsoleToolWindow = dte.Windows.Item("{0AD07096-BBA9-4900-A651-0598D26F6D24}");
            powerConsoleToolWindow.Visible = true;
        }

        internal void ExecuteCommand(string command, bool clearFirst = true)
        {
            command  = command.Trim().Replace(Environment.NewLine, "");
            if (clearFirst) {
                wpfConsole.GetType().GetMethod("ClearConsole").Invoke(wpfConsole, null);
            }

            // create a input line
            Type typeInputLine = powerConsoleToolWindow.GetType().Assembly.GetType("NuGetConsole.Implementation.Console.InputLine");
            var inputline = Activator.CreateInstance(typeInputLine, BindingFlags.Instance | BindingFlags.Public, null, new object[] { command, true }, null);

            // execute input line
            var result = dispatch.GetType().GetMethod("PostInputLine").Invoke(dispatch, new object[] { inputline });
        }
    }
}
